package com.le.tester.imooc.oldfairy.coding.stream;

import org.junit.Test;

import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * createTime：2023/4/26 16:29
 * description：base stream
 */
public class BasicExamples {

    @Test
    public void testParallel() throws ExecutionException, InterruptedException {
        Random random = new Random();

        List<Integer> collect = IntStream.range(0, 1_000_000)
                .map(item -> random.nextInt(1_000_000))
                .boxed()
                .collect(Collectors.toList());

        long startTime = System.currentTimeMillis();

        System.out.println(collect.stream().max(Comparator.comparing(item -> item)));
        System.out.println("time is " + (System.currentTimeMillis() - startTime));


        //stream中的parallel中的多线程
        ForkJoinPool forkJoinPool = new ForkJoinPool(2);
        long startTimeP = System.currentTimeMillis();
        //split data,merge data,split size is 1024
        System.out.println(forkJoinPool.submit(() -> collect.parallelStream().max(Comparator.naturalOrder())).get());

        System.out.println("parallel time is " + (System.currentTimeMillis() - startTimeP));
    }
}
